package hai.com.android_test.widget.calendarView;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import hai.com.android_test.R;
import hai.com.android_test.adapter.MyBaseAdapter;
import hai.com.android_test.widget.AutoGridView;

/**
 * Created by 黄海 on 2017/6/20.
 */

public class CalendarItem extends LinearLayout {
    private static final String TAG = "CalendarItem";
    private ArrayList<Integer> datas = new ArrayList<>(0);
    private BaseAdapter adapter;
    private Calendar currentDate = Calendar.getInstance();
    private int index;
    @BindView(R.id.gridView)
    AutoGridView gridView;
    //当月天数
    private int daysOfMonth;
    // 当前月第一天星期几
    private int firstDayOfWeek;

    public CalendarItem(Context context) {
        this(context, null);
    }

    private CalendarItem(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    private CalendarItem(final Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        LayoutInflater.from(context).inflate(R.layout.item_calendar, this, true);
        ButterKnife.bind(this);
        gridView.setAdapter(adapter = new MyBaseAdapter<Integer>(getContext(), datas) {
            @Override
            public int getCount() {
                return 42;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_day, null);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.tv_day);
                int num = position - firstDayOfWeek + 2;
                if (num < 1 || num > daysOfMonth) tv.setText(null);
                else tv.setText(String.valueOf(num));
                return convertView;
            }
        });
        updateDate(currentDate);
    }

    public void updateDate(Calendar dst_date) {
        if (dst_date != null && currentDate.compareTo(dst_date) != 0) {
            currentDate = (Calendar) dst_date.clone();
            firstDayOfWeek = currentDate.get(Calendar.DAY_OF_WEEK);
            daysOfMonth = currentDate.getActualMaximum(Calendar.DAY_OF_MONTH);
            adapter.notifyDataSetChanged();
        }
    }

    public Calendar getCurrentDate() {
        return (Calendar) currentDate.clone();
    }

    public void setIndex(int index) {
        this.index = index;
    }
}
